local jieliu = fk.CreateSkill {
  name = "th_jieliu",
  derived_piles = "th_nitori_xie",
}

local ThU = require "packages/2hu/pkg/util/th_util"
jieliu:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(jieliu.name) then return end
    local room = player.room
    local ids = {}
    local move_event = room.logic:getCurrentEvent()
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          local card = Fk:getCardById(info.cardId)
          if card.type == Card.TypeEquip and player.room:getCardArea(info.cardId) == Card.DiscardPile then
            table.insert(ids, info.cardId)
          end
        end
      end
    end

    if #ids > 0 then
      event:setSkillData(self, "th_jieliu_" .. player.id .. ":" .. move_event.id, ids)
      return true
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local markname = "th_jieliu_" .. player.id .. ":" .. player.room.logic:getMostRecentEvent(GameEvent.MoveCards).id
    local ret = event:getSkillData(self, markname)

    for _, cid in ipairs(ret) do
      event:setSkillData(self, "cancel_cost", false)
      if #player:getPile("th_nitori_xie") >= 4 then break end
      if not player:hasSkill(jieliu.name) then break end

      -- 判断此牌最后一次离开【手牌区+装备区】进入非角色区域时位于谁的区域
      if ThU.getCardLastOwner(player.room, cid) == player then
        goto continue
      end

      event:setCostData(self, cid)
      self:doCost(event, target, player, data)

      ::continue::
      event:setSkillData(self, "cancel_cost", false)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local cid = event:getCostData(self)
    return player.room:askToSkillInvoke(player, {
      skill_name = jieliu.name,
      prompt = "#th_jieliu-invoke:::"..Fk:getCardById(cid):toLogString()
    })
  end,
  on_use = function(self, event, target, player, data)
    local cid = event:getCostData(self)
    player:addToPile("th_nitori_xie", cid, true, jieliu.name, player, player.room:getAllPlayers())
    player:drawCards(1, jieliu.name)
  end
})

Fk:loadTranslationTable{
  ["th_jieliu"] = "解流",
  [":th_jieliu"] = "一张不属于你的装备牌进入弃牌堆后，你可以将之置于你的武将牌上称之为“械”（至多四张），然后摸一张牌。",

  ["#th_jieliu-invoke"] = "解流：你可以将 %arg 置于你的武将牌上称之为“械”（至多四张），然后摸一张牌",

  ["th_nitori_xie"] = "械",
}

return jieliu